package ntu.edu.cn.action;

import ntu.edu.cn.pojo.User;
import ntu.edu.cn.util.DownloadYZM;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Morven Qiu on 8/10/2016.
 */
public class LoginAction extends BaseAction  {

    private static final Logger logger = Logger.getLogger(BaseAction.class);
    private User user;
    /**
     * get the verification and transfer it to the app
     */
    public void getVerification() {
        HttpSession session = getSession();
        HttpServletResponse httpResponse = ServletActionContext.getResponse();
        BasicCookieStore basicCookieStore = new BasicCookieStore();
        try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(httpResponse.getOutputStream());
             CloseableHttpClient closeableHttpClient = getHttpClient().setDefaultCookieStore(basicCookieStore).build();
             InputStream inputStream = DownloadYZM.downloadFile(closeableHttpClient)) {
            if (inputStream != null) {
                httpResponse.setContentType("image/gif");//设置response内容的类型
                int bytesRead;
                byte[] buffer = new byte[3000];
                while ((bytesRead = inputStream.read(buffer, 0, 3000)) != -1) {
                    bufferedOutputStream.write(buffer, 0, bytesRead);
                }
                bufferedOutputStream.flush();
            } else {
                httpResponse.getWriter().write("error,please try again!");
            }
            session.setAttribute("basicCookieStore", basicCookieStore);
        } catch (IOException e) {
            logger.error("error to get verification code");
            getWriter().print("error");
        }
    }

    /**
     * login validation
     * @throws IOException
     */
    public void checkLogin() throws IOException {
        HttpPost httpPost = new HttpPost("http://jwgl.ntu.edu.cn/cjcx/Default.aspx");
        configParam(httpPost);
        List<NameValuePair> formparams = new ArrayList<>();
        formparams.add(new BasicNameValuePair("__VIEWSTATE", "/wEPDwUJODExMDE5NzY5ZGRgtUdRucUbXsT8g55XmVsTwV6PMw=="));
        formparams.add(new BasicNameValuePair("__VIEWSTATEGENERATOR", "6C0FF253"));
        formparams.add(new BasicNameValuePair("xh", user.getId()));
        formparams.add(new BasicNameValuePair("sfzh", user.getIdentityId()));
        formparams.add(new BasicNameValuePair("kl", user.getPassword()));
        formparams.add(new BasicNameValuePair("yzm", user.getVerificationCode()));
        try (CloseableHttpClient closeableHttpClient = getClosableHttpClient()){
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httpPost.setEntity(entity);
            HttpResponse response = closeableHttpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            logger.info("this request return the code is *** " + code);
            if (code == 302) {
                String location = "http://jwgl.ntu.edu.cn/cjcx/Main.aspx";
                HttpGet httpGet = new HttpGet(location);
                //httpGet.setHeader("Accept","text/html, application/xhtml+xml, */*");
                httpGet.setHeader("Referer", "http://jwgl.ntu.edu.cn/cjcx/Default.aspx");
                httpGet.setHeader("Accept-Language", "en-US");
                //httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko");
                //httpGet.setHeader("Accept-Encoding","gzip,deflate");
                httpGet.setHeader("Proxy-Connection", "Keep-Alive");
                httpGet.setHeader("DNT", "1");
                httpGet.setHeader("HOST", "jwgl.ntu.edu.cn");
                configParam(httpGet);
                //httpGet.setHeader("Pragma", "no-cache");
                //httpGet.setHeader("Content-Length", "0");
                HttpResponse response1 = closeableHttpClient.execute(httpGet);
                logger.info("the httpget return a code status " + response1.getStatusLine().getStatusCode());
                String html = EntityUtils.toString(response1.getEntity());
                getWriter().print(html);
            }else if(code == 200){
                String html = EntityUtils.toString(response.getEntity());
                getWriter().print(html);
            }
        } catch (IOException e) {
            logger.error("something error when user tried to log in !!!");
            getWriter().print("error");
        }
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
